//
//  SEGSessionMessageViewModel.m
//  SEGViewModel
//
//  Created by 乔杨 on 2020/6/9.
//

#import "SEGSessionMessageViewModel.h"
#import "MessageDataBaseModel.h"
#import "MessageRequestModel.h"

@interface SEGSessionMessageViewModel ()

/// groupID
@property (nonatomic, strong) MessageModel *msgModel;

@end

@implementation SEGSessionMessageViewModel

- (instancetype)initWithMessageModel:(MessageModel *)msgModel {
    self = [super init];
    if (self) {
        self.msgModel = msgModel;
        self.messageArray = [[NSMutableArray alloc] initWithArray:[[MessageDataBaseModel sharedDataBaseModel] getMessageWithGroupId:self.msgModel.groupid]];
        [self seg_createReceiveSignal];
        [self seg_createSendMsgCommand];
    }
    return self;
}
- (void)seg_createReceiveSignal {
    @weakify(self);
    self.receiveSignal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        @strongify(self);
        [[MessageRequestModel sharedRequestModel] requestMessageList:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
            if (isSuccessed) {
                // 消息及时刷新
                self.messageArray = [[NSMutableArray alloc] initWithArray:[[MessageDataBaseModel sharedDataBaseModel] getMessageWithGroupId:self.msgModel.groupid]];
                // 修改这个页面上的所有消息为已读 防止在本页读消息时收到新消息返回消息中心时新消息仍为未读
                [[MessageDataBaseModel sharedDataBaseModel] updateMessagesToReadInDataBaseWithGroupId:self.msgModel.groupid];
            }
            [subscriber sendNext:@""];
            [subscriber sendCompleted];
        }];
        
        return nil;
    }];
}
- (void)seg_createSendMsgCommand {
    @weakify(self);
    self.sendMsgCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(NSString *message) {
        return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
            @strongify(self);
            NSArray *arr = [self.msgModel.groupid componentsSeparatedByString:@"-"];
            if (arr.count == 2) { // 闲置格式
                NSString *objectId = [arr objectAtIndex:1];
                NSString *str = [arr objectAtIndex:0];
                NSArray *typeArr = [str componentsSeparatedByString:@"|"];
                NSString *type = [typeArr objectAtIndex:2];
                if ([type isEqualToString:@"100320"]) {
                    [[MessageRequestModel sharedRequestModel] requestPushMessageForChat:@"0" contentType:@"1" userId:self.msgModel.sendUserId title:kAccountNickName description:message content:message type:@"100320" serviceId:objectId from:@"1" groupId:nil provider:nil finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
                        if (isSuccessed) {
                            [self saveMessageWithString:message];
                            [subscriber sendNext:@""];
                            [subscriber sendCompleted];
                        } else {
                            NSError *error = [NSError errorWithDomain:@"" code:0 userInfo:@{NSLocalizedFailureReasonErrorKey:errorMessage}];
                            [subscriber sendError:error];
                        }
                    }];
                }
            } else { //聊天类型 拼车。。。
                [[MessageRequestModel sharedRequestModel] requestPushMessageForChat:@"0" contentType:@"1" userId:self.msgModel.sendUserId title:kAccountNickName description:message content:message type:@"101800" serviceId:@"1" from:@"1" groupId:nil provider:nil finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
                    if (isSuccessed) {
                        [self saveMessageWithString:message];
                        [subscriber sendNext:@""];
                        [subscriber sendCompleted];
                    }else {
                        NSError *error = [NSError errorWithDomain:@"" code:0 userInfo:@{NSLocalizedFailureReasonErrorKey:errorMessage}];
                        [subscriber sendError:error];
                    }
                }];
            }
            
            return nil;
        }];
    }];
}
- (void)saveMessageWithString:(NSString *)string {
    MessageModel *message = [[MessageModel alloc] init];
    message.userid = self.msgModel.sendUserId;
    message.message = string;
    message.contenttype = @"1";
    message.createTime = [SEGUtils stringDateByFormatString:@"yyyy-MM-dd HH:mm" withDate:[NSDate date]];
    message.groupid = self.msgModel.groupid;
    message.businesstype = self.msgModel.businesstype;
    message.sendUserType = @"0";
    message.sendUserId = self.msgModel.userid;
    message.isRead = @"1";
    message.objectid = self.msgModel.objectid;
    message.uuid = kAccountUserID;
    message.communityId = kAccountCommunityID;
    
    [[MessageDataBaseModel sharedDataBaseModel] saveMessageWithModel:message];
    [self.messageArray addObject:message];
}

@end
